<template>
  <div class="expiring-tenants">
    <el-alert
      title="即将到期提醒"
      type="warning"
      description="以下租户即将到期，请及时处理续费事宜"
      show-icon
      :closable="false"
      class="alert-header"
    />
    
    <el-table :data="expiringTenants" v-loading="loading" class="expiring-table">
      <el-table-column label="租户编码" prop="tenantCode" width="120" />
      <el-table-column label="租户名称" prop="tenantName" :show-overflow-tooltip="true" />
      <el-table-column label="租户类型" prop="tenantType" width="100">
        <template #default="scope">
          <el-tag :type="getTenantTypeTag(scope.row.tenantType)">
            {{ getTenantTypeName(scope.row.tenantType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="联系人" prop="contactName" width="100" />
      <el-table-column label="联系邮箱" prop="contactEmail" width="180" :show-overflow-tooltip="true" />
      <el-table-column label="到期时间" prop="expireTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expireTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="剩余天数" prop="remainingDays" width="100">
        <template #default="scope">
          <el-tag :type="getRemainingDaysTag(scope.row.remainingDays)">
            {{ scope.row.remainingDays }}天
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTag(scope.row.status)">
            {{ scope.row.statusName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            @click="handleRenew(scope.row)"
          >续费</el-button>
          <el-button 
            type="info" 
            size="small" 
            @click="handleNotify(scope.row)"
          >通知</el-button>
          <el-button 
            type="warning" 
            size="small" 
            @click="handleExtend(scope.row)"
          >延期</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div v-if="!loading && expiringTenants.length === 0" class="empty-state">
      <el-empty description="暂无即将到期的租户" />
    </div>
    
    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-statistic title="即将到期" :value="stats.expiringSoon" suffix="个" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="7天内到期" :value="stats.within7Days" suffix="个" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="30天内到期" :value="stats.within30Days" suffix="个" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="已过期" :value="stats.expired" suffix="个" />
        </el-col>
      </el-row>
    </div>

    <!-- 续费对话框 -->
    <el-dialog title="租户续费" v-model="renewDialogVisible" width="600px">
      <el-form ref="renewFormRef" :model="renewForm" :rules="renewRules" label-width="100px">
        <el-form-item label="租户名称">
          <el-input v-model="currentTenant.tenantName" disabled />
        </el-form-item>
        <el-form-item label="当前到期时间">
          <el-input :value="parseTime(currentTenant.expireTime)" disabled />
        </el-form-item>
        <el-form-item label="续费时长" prop="renewalPeriod">
          <el-select v-model="renewForm.renewalPeriod" placeholder="请选择续费时长">
            <el-option label="1个月" :value="1" />
            <el-option label="3个月" :value="3" />
            <el-option label="6个月" :value="6" />
            <el-option label="1年" :value="12" />
            <el-option label="2年" :value="24" />
            <el-option label="3年" :value="36" />
          </el-select>
        </el-form-item>
        <el-form-item label="新到期时间">
          <el-input :value="getNewExpireTime()" disabled />
        </el-form-item>
        <el-form-item label="续费备注" prop="remark">
          <el-input v-model="renewForm.remark" type="textarea" :rows="3" placeholder="请输入续费备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitRenewal" :loading="renewLoading">确认续费</el-button>
          <el-button @click="renewDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 延期对话框 -->
    <el-dialog title="租户延期" v-model="extendDialogVisible" width="600px">
      <el-form ref="extendFormRef" :model="extendForm" :rules="extendRules" label-width="100px">
        <el-form-item label="租户名称">
          <el-input v-model="currentTenant.tenantName" disabled />
        </el-form-item>
        <el-form-item label="当前到期时间">
          <el-input :value="parseTime(currentTenant.expireTime)" disabled />
        </el-form-item>
        <el-form-item label="延期天数" prop="extendDays">
          <el-input-number v-model="extendForm.extendDays" :min="1" :max="365" style="width: 100%" />
        </el-form-item>
        <el-form-item label="新到期时间">
          <el-input :value="getNewExtendTime()" disabled />
        </el-form-item>
        <el-form-item label="延期原因" prop="reason">
          <el-input v-model="extendForm.reason" type="textarea" :rows="3" placeholder="请输入延期原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitExtension" :loading="extendLoading">确认延期</el-button>
          <el-button @click="extendDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { parseTime } from '@/utils'
import { 
  getExpiringSoonTenants, 
  getExpiredTenants,
  updateTenant
} from '@/api/tenant'

// Emits
const emit = defineEmits(['close'])

// 响应式数据
const loading = ref(true)
const renewLoading = ref(false)
const extendLoading = ref(false)
const renewDialogVisible = ref(false)
const extendDialogVisible = ref(false)
const expiringTenants = ref([])
const currentTenant = ref({})

// 表单引用
const renewFormRef = ref()
const extendFormRef = ref()

// 统计信息
const stats = reactive({
  expiringSoon: 0,
  within7Days: 0,
  within30Days: 0,
  expired: 0
})

// 续费表单
const renewForm = reactive({
  renewalPeriod: 12,
  remark: ''
})

// 延期表单
const extendForm = reactive({
  extendDays: 30,
  reason: ''
})

// 续费表单验证规则
const renewRules = reactive({
  renewalPeriod: [
    { required: true, message: '请选择续费时长', trigger: 'change' }
  ]
})

// 延期表单验证规则
const extendRules = reactive({
  extendDays: [
    { required: true, message: '请输入延期天数', trigger: 'blur' },
    { type: 'number', min: 1, max: 365, message: '延期天数必须在1-365之间', trigger: 'blur' }
  ],
  reason: [
    { required: true, message: '请输入延期原因', trigger: 'blur' }
  ]
})

// 获取即将到期的租户
const getExpiringTenants = async () => {
  try {
    loading.value = true
    const response = await getExpiringSoonTenants()
    expiringTenants.value = response.data
    
    // 计算统计信息
    calculateStats()
  } catch (error) {
    ElMessage.error('获取即将到期租户失败')
  } finally {
    loading.value = false
  }
}

// 计算统计信息
const calculateStats = () => {
  stats.expiringSoon = expiringTenants.value.length
  stats.within7Days = expiringTenants.value.filter(t => t.remainingDays <= 7).length
  stats.within30Days = expiringTenants.value.filter(t => t.remainingDays <= 30).length
  stats.expired = expiringTenants.value.filter(t => t.remainingDays <= 0).length
}

// 续费操作
const handleRenew = (row) => {
  currentTenant.value = row
  renewForm.renewalPeriod = 12
  renewForm.remark = ''
  renewDialogVisible.value = true
}

// 通知操作
const handleNotify = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确认要发送到期提醒通知给租户"${row.tenantName}"吗？`,
      '发送通知',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 这里应该调用发送通知的API
    ElMessage.success('通知发送成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('通知发送失败')
    }
  }
}

// 延期操作
const handleExtend = (row) => {
  currentTenant.value = row
  extendForm.extendDays = 30
  extendForm.reason = ''
  extendDialogVisible.value = true
}

// 提交续费
const submitRenewal = () => {
  renewFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        renewLoading.value = true
        
        // 计算新的到期时间
        const currentExpire = new Date(currentTenant.value.expireTime)
        const newExpire = new Date(currentExpire)
        newExpire.setMonth(newExpire.getMonth() + renewForm.renewalPeriod)
        
        // 更新租户信息
        await updateTenant({
          id: currentTenant.value.id,
          expireTime: newExpire.toISOString()
        })
        
        ElMessage.success('续费成功')
        renewDialogVisible.value = false
        getExpiringTenants()
      } catch (error) {
        ElMessage.error('续费失败')
      } finally {
        renewLoading.value = false
      }
    }
  })
}

// 提交延期
const submitExtension = () => {
  extendFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        extendLoading.value = true
        
        // 计算新的到期时间
        const currentExpire = new Date(currentTenant.value.expireTime)
        const newExpire = new Date(currentExpire)
        newExpire.setDate(newExpire.getDate() + extendForm.extendDays)
        
        // 更新租户信息
        await updateTenant({
          id: currentTenant.value.id,
          expireTime: newExpire.toISOString()
        })
        
        ElMessage.success('延期成功')
        extendDialogVisible.value = false
        getExpiringTenants()
      } catch (error) {
        ElMessage.error('延期失败')
      } finally {
        extendLoading.value = false
      }
    }
  })
}

// 计算新的到期时间（续费）
const getNewExpireTime = () => {
  if (!currentTenant.value.expireTime || !renewForm.renewalPeriod) return ''
  const currentExpire = new Date(currentTenant.value.expireTime)
  const newExpire = new Date(currentExpire)
  newExpire.setMonth(newExpire.getMonth() + renewForm.renewalPeriod)
  return parseTime(newExpire)
}

// 计算新的到期时间（延期）
const getNewExtendTime = () => {
  if (!currentTenant.value.expireTime || !extendForm.extendDays) return ''
  const currentExpire = new Date(currentTenant.value.expireTime)
  const newExpire = new Date(currentExpire)
  newExpire.setDate(newExpire.getDate() + extendForm.extendDays)
  return parseTime(newExpire)
}

// 获取租户类型名称
const getTenantTypeName = (type) => {
  const typeMap = {
    1: '企业版',
    2: '个人版',
    3: '试用版'
  }
  return typeMap[type] || '未知'
}

// 获取租户类型标签
const getTenantTypeTag = (type) => {
  const tagMap = {
    1: 'primary',
    2: 'success',
    3: 'warning'
  }
  return tagMap[type] || 'info'
}

// 获取状态标签
const getStatusTag = (status) => {
  const tagMap = {
    0: 'danger',
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return tagMap[status] || 'info'
}

// 获取剩余天数标签
const getRemainingDaysTag = (days) => {
  if (days <= 0) return 'danger'
  if (days <= 7) return 'danger'
  if (days <= 30) return 'warning'
  return 'success'
}

// 组件挂载时获取数据
onMounted(() => {
  getExpiringTenants()
})
</script>

<style lang="scss" scoped>
.expiring-tenants {
  .alert-header {
    margin-bottom: 20px;
  }
  
  .expiring-table {
    margin-bottom: 20px;
  }
  
  .empty-state {
    text-align: center;
    padding: 40px 0;
  }
  
  .stats-section {
    margin-top: 30px;
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 4px;
  }
  
  .dialog-footer {
    text-align: right;
    
    .el-button {
      margin-left: 10px;
    }
  }
}

:deep(.el-statistic__content) {
  text-align: center;
}
</style>
